-module(vendor_adapter).
-include("rec_dec.hrl").
-export([add/1,get/1,get/2,addchange/1,del/1,get_queue_inst_list/2,ui/2,cfg/1,reset/1,toHtml/2]).

add(Rec) when is_record(Rec,vendor_rec) ->
	db_mgr:add(Rec).

addchange(L) when is_list(L)->
	Id = tools:get_param(L,"vendor_id",""),
	Vendor = vendor_service:get(Id),
	Name = tools:get_param(L,"name",Vendor#vendor_rec.name),
	Short_Name = tools:get_param(L,"short_name",Vendor#vendor_rec.short_name),
	Desc = tools:get_param(L,"desc",Vendor#vendor_rec.desc),
	Addr = tools:get_param(L,"addr",Vendor#vendor_rec.addr),
	Contactor = tools:get_param(L,"contactor",Vendor#vendor_rec.contactor),
	Mobile_Phone = tools:get_param(L,"phone",Vendor#vendor_rec.mobile_phone),
	Force_Default = case tools:get_param(L,"create_default","off") of
					"off" ->
						false;
					"on" ->
						true;
					_ ->
						false
					end,
	addchange({Force_Default,#vendor_rec{name=Name,
						short_name = Short_Name,
						desc=Desc,
						contactor=Contactor,
						mobile_phone=Mobile_Phone,
						addr=Addr,
						register_id = session_service:getLoginedInfo(L,user_id),
						id=case Id of 
							"" -> "";
							S -> list_to_binary(S)
						end
						}});
addchange({false,V}) when is_record(V,vendor_rec) ->
	{html,rfc4627:encode(tojson(vendor_service:addchange(V)))};
	
addchange({true,V}) when is_record(V,vendor_rec) ->
	NewV = vendor_service:addchange(V),
	gen_server:call(biz_vendor,{add,NewV}),
	queue_adapter:addchange((queue_adapter:template(two_seat))#queue_rec{
		vendor_id = NewV#vendor_rec.id
	}),
	queue_adapter:addchange((queue_adapter:template(three_to_four_seat))#queue_rec{
		vendor_id = NewV#vendor_rec.id
	}),
	queue_adapter:addchange((queue_adapter:template(mid_seat))#queue_rec{
		vendor_id = NewV#vendor_rec.id
	}),
	queue_adapter:addchange((queue_adapter:template(big_seat))#queue_rec{
		vendor_id = NewV#vendor_rec.id
	}),
	{html,rfc4627:encode(tojson(NewV))}.
	
reset(Req) ->
	{"password",Pwd} = lists:keyfind("password",1,Req),
	{"id",Id} = lists:keyfind("id",1,Req),
	gen_server:call(biz_vendor,{reset_inst,list_to_binary(Id)}),
	{html,"ok"}.

cfg(Req) ->
	{value,{"id",Id}} = lists:keysearch("id",1,Req),
	{value,{"out_notify",OutNotify}} = lists:keysearch("out_notify",1,Req),
	{value,{"in_notify",InNotify}} = lists:keysearch("in_notify",1,Req),
	{value,{"pre_out_notify",PreOutNotify}} = lists:keysearch("pre_out_notify",1,Req),
	{value,{"pre_out_notify_cond",Cond}} = lists:keysearch("pre_out_notify_cond",1,Req),
	Res = vendor_service:addchange(
				#vendor_cfg{id=list_to_binary(Id),
						out_notify = (OutNotify),
						in_notify=(InNotify),
						pre_out_notify = (PreOutNotify),
						pre_out_notify_cond=list_to_integer(Cond)
						}
				),
	gen_server:call(biz_vendor,{forward_vendor_msg,Res#vendor_cfg.id,{update_cfg,Res}}),
	{html,rfc4627:encode(tojson(Res))}.

get(option_list) ->
	L = vendor_service:get(),
	lists:map(fun(R) ->
						{option,[{value,binary_to_list(R#vendor_rec.id)}],(R#vendor_rec.name)}
						end,
			  L);
get(L) ->
	rfc4627:encode({
	obj,[{"aaData",
		lists:map(
			fun(E) ->
				tojson(E)
			end,
			vendor_service:get({
				register,
				session_service:getLoginedInfo(L,user_id)
			}))}
		]
	}).
get(html_list,L) ->
	{ehtml,
		{
			'div',[{class,"list"},{id,"vendor_list"}],
				lists:map(
				fun(E) ->
					io:format("toHtml called!n"),
					toHtml(list,E)
				end,
				vendor_service:get({
					register,
					session_service:getLoginedInfo(L,user_id)
				})
				)
		}
	};
get(mobile_select_list,L) ->
	{ehtml,
		{'ul',[{'data-role',"listview"}],
			lists:map(fun({_,V,_}) ->
						toHtml(mobile_list,V)
				      end,
				      vendor_service:get({managedby_only,session_service:getLoginedInfo(L,user_id)})
				      )
		}

	};
get(html_table,L) ->
	{ehtml,
		{'div',[],[{table,[],
		lists:map(
			fun({E,T}) ->
				toHtml(table_rec,{E,T})
			end,
			vendor_service:get({
				managedby,
				list_to_binary(tools:get_param(L,"user_id",""))	
				})
			)
		}]}

	};
get(option_list,Vendor_Id) ->
	L = vendor_service:get(),
	V = list_to_binary(Vendor_Id),
	lists:map(fun(R) ->
						if 
							R#vendor_rec.id =:= V ->
								{option,[{value,binary_to_list(R#vendor_rec.id)},{selected,"selected"}],(R#vendor_rec.name)};
							true ->
								{option,[{value,binary_to_list(R#vendor_rec.id)}],(R#vendor_rec.name)}
						end
				end,
			  L);
get(managed_by,User_Id) ->
	vendor_service:get({
				managedby,
				list_to_binary(User_Id)	
				});
get(detail_vendors,Register_Id) ->
	lists:map(
			fun(E) ->
				{E,session_service:get(login_info,E),biz_vendor:get(queue_info,E)}
			end,
			vendor_service:get({
					register,
					list_to_binary(Register_Id)})
	);
get(entity,Vendor_Id) ->
	case list_to_binary(Vendor_Id) of
	<<"">> ->
		#vendor_rec{id=list_to_binary("")};
	Id ->
		vendor_service:get(Id)
	end.
	
del(L) ->
	{value,{"id",Id}} = lists:keysearch("id",1,L),
	vendor_service:del(list_to_binary(Id)),
	{html,rfc4627:encode({obj,[{"result","OK"}]})}.
	
list() ->
	{html,list(json)}.
list(json) ->
	L = vendor_service:get(),
	J_Objs = lists:map(fun(R) ->
						tojson(R)
						end,
					L),
    rfc4627:encode({obj,[{"aaData",J_Objs}]}).

toHtml(list,E) when is_record(E,vendor_rec) ->
	{'div',[{'class',"vendor"}],[
		{h3,[],[{a,[{href,io_lib:format("/www/pages/vendor_page.yaws?vendor_id=~s",[E#vendor_rec.id])}],E#vendor_rec.name}]},
		{p,[],io_lib:format("地址:~s",[E#vendor_rec.addr])},
		{p,[],io_lib:format("电话:~s 联系人:~s ",[E#vendor_rec.mobile_phone,E#vendor_rec.contactor])}
	]};
toHtml(view,E) when is_record(E,vendor_rec) ->
	{'div',[],[
		{table,[],[
			{tr,[],[]},
			{tr,[],[]},
			{tr,[],[]}
		]}
		]
	};
toHtml(table_rec,{E,T}) when is_record(E,vendor_rec) ->
	{'tr',[],[
		{'td',[],E#vendor_rec.name},
		{'td',[],E#vendor_rec.addr},
		{'td',[],[{input,case T of 
						 true ->
							[{type,"checkbox"},{class,"managedby"},{'id',binary_to_list(E#vendor_rec.id)},{checked,"true"}];
						false ->
							[{type,"checkbox"},{class,"managedby"},{'id',binary_to_list(E#vendor_rec.id)}]
						end,
					"选择"}
				 ]
		}
	]};
toHtml(mobile_list,V) when is_record(V,vendor_rec) ->
%%io_lib:format("/mobile/select_vendor_act.yaws?vendor_id=~s",[binary_to_list(V#vendor_rec.id)])
	{'li',[],[
		{a,[{href,"javascript:void(0)"},{class,"select_item"},{id,binary_to_list(V#vendor_rec.id)}],V#vendor_rec.name}
	]};
toHtml(edit,E) when is_record(E,vendor_rec) ->
	{'div',[],[
		{form,[{action,"/www/queue_act.yaws?mod=vendor&action=addchange"},{method,"get"}],
              [
			   {input,[{name,"vendor_id"},{'id',"vendor_id"},{value,binary_to_list(E#vendor_rec.id)},{type,"hidden"}],[]},
               {table,[],[
                         {tr,[],[{td,[],"名称"},{td,[],[{input,[{name,"name"},{value,E#vendor_rec.name}],[]}]}]},
                         {tr,[],[{td,[],"简称"},{td,[],[{input,[{name,"short_name"},{value,E#vendor_rec.short_name}],[]}]}]},
                         {tr,[],[{td,[],"地址"},{td,[],[{input,[{name,"addr"},{value,E#vendor_rec.addr}],[]}]}]},
                         {tr,[],[{td,[],"电话"},{td,[],[{input,[{name,"phone"},{value,E#vendor_rec.mobile_phone}],[]}]}]},
                         {tr,[],[{td,[],"联系人"},{td,[],[{input,[{name,"contactor"},{value,E#vendor_rec.contactor}]}]}]},
                        {tr,[],[{td,[],"备注"},{td,[],[{textarea,[{name,"desc"},{value,E#vendor_rec.desc}],[]}]}]}
                        ] ++ case binary_to_list(E#vendor_rec.id) of 
                           "" ->
                           		[{tr,[],[{td,[],""},{td,[],[{input,[{name,"create_default"},{type,"checkbox"}],"创建缺省队列"}]}]}];
                           _ ->
                           		[]
                           	end
               }
             ]
		}
		]
	}.
tojson(R) when is_record(R,vendor_rec) ->
	{obj,
		[
			{
				"id",R#vendor_rec.id
			},
			{
				"short_name",list_to_binary(R#vendor_rec.short_name)
			},
			{
                "name",list_to_binary(R#vendor_rec.name)
            }
            ,{
                "desc",list_to_binary(R#vendor_rec.desc)
            }
            ,{
                "contactor",list_to_binary(R#vendor_rec.contactor)
            }
            ,{
                "phone",list_to_binary(R#vendor_rec.mobile_phone)
            }
			,{
                "addr",list_to_binary(R#vendor_rec.addr)
            }
        ]
    };
tojson(R) when is_record(R,vendor_cfg) ->
	{obj,[
		{
			"id",R#vendor_cfg.id
		},
		{
			"out_notify",R#vendor_cfg.out_notify
		},
		{
			"in_notify",R#vendor_cfg.in_notify
		},
		{
			"pre_out_notify_cond",R#vendor_cfg.pre_out_notify_cond
		}
	]};
tojson(R) when is_record(R,queue_inst_rec) ->
	[Q|_] = queue_service:get({id,R#queue_inst_rec.id}),
	io:format("convert the queue ~p~n",[Q]),
	{
		obj,[
			{"id",R#queue_inst_rec.id},
			{"name",list_to_binary(R#queue_inst_rec.name)},
			{"in_q_num",R#queue_inst_rec.in_q_num},
			{"cur_index",R#queue_inst_rec.in_q_num},
			{"icon_type",list_to_binary(Q#queue_rec.icon_type)},
			{"prefix",list_to_binary(Q#queue_rec.prefix)},
			json_util:tojson("adv_val",Q#queue_rec.notify_cond)
		]
	}.
%%get_queue_inst_list(html,Id) ->
%%	{ethtml,
%%	case gen_servier:call(biz_vendor,{vendor,Id,{queue,list}}) of
%%		[{}]
%%	end
%%	}
get_queue_inst_list(json,Id) ->
	rfc4627:encode({
		obj,
		case gen_server:call(biz_vendor,{vendor,Id,{queue,list}}) of
		{error,Reason} ->
			[{"result","error"},{"reason",io_lib:format("retrieve ~p for queue failed with ~s~n",[Id,Reason])}];
		{ok,L} ->
			[
				{"data",lists:map(fun(R) ->
						tojson(R)
						end,
					L)},
				{"result","ok"}
			]
		end}).

notifyOption("sms",sms) ->
	{option,[{value,"sms"},{selected,""}],"短信"};
notifyOption(_,sms) ->
	{option,[{value,"sms"}],"短信"};
	
notifyOption("weibo",weibo) ->
	{option,[{value,"weibo"},{selected,""}],"微博"};
notifyOption(_,weibo) ->
	{option,[{value,"weibo"}],"微博"};

notifyOption("none",none) ->
	{option,[{value,"none"},{selected,""}],"不需要"};
notifyOption(_,none) ->
	{option,[{value,"none"}],"不需要"}.
	
toForm(E) when is_record(E,vendor_rec) ->
	{form,[{id,"basic_info"}],[
		{table,[],[
		{tr,[],[{td,[],"名称"},
				{td,[],[{input,[{value,E#vendor_rec.name},{name,"name"}],[]}]},
				{td,[],"简称"},
				{td,[],[{input,[{value,E#vendor_rec.short_name},{name,"short_name"}],[]}]}
				]}
		,{tr,[],[{td,[],"联系人"},
				{td,[],[{input,[{value,E#vendor_rec.contactor},{name,"contactor"}],[]}]},
				{td,[],"电话"},
				{td,[],[{input,[{value,E#vendor_rec.mobile_phone},{name,"phone"}],[]}]}
				]}
		,{tr,[],[{td,[],"地址"},
				{td,[],[{input,[{value,E#vendor_rec.addr},{name,"addr"}],[]}]}
				,{td,[],[]},{td,[],[]}]}
		,{tr,[],[{td,[],"描述信息"},
				{td,[],[{textarea,[{value,E#vendor_rec.desc},{name,"desc"}],[]}]}
				,{td,[],[]},{td,[],[]}]}
		]},
		{input,[{type,"submit"},{value,"提交"}],[]}
	]};
toForm(C) when is_record(C,vendor_cfg) ->
	{form,[{id,"cfg_info"}],[{table,[],[
		{tr,[],[
			{td,[],"入队通知"},
			{td,[],[{select,[{name,"in_notify"}],[
							notifyOption(C#vendor_cfg.in_notify,sms),
							notifyOption(C#vendor_cfg.in_notify,weibo),
							notifyOption(C#vendor_cfg.in_notify,none)
							]}]},
			{td,[],"出队通知"},
			{td,[],[{select,[{name,"out_notify"}],[
							notifyOption(C#vendor_cfg.out_notify,sms),
							notifyOption(C#vendor_cfg.out_notify,weibo),
							notifyOption(C#vendor_cfg.out_notify,none)
							]}]}
		]},
		{tr,[],[
			{td,[],"提前通知"},
			{td,[],[{select,[{name,"pre_out_notify"}],[
							notifyOption(C#vendor_cfg.pre_out_notify,sms),
							notifyOption(C#vendor_cfg.pre_out_notify,weibo),
							notifyOption(C#vendor_cfg.pre_out_notify,none)
							]}]},
			{td,[],"提前量"},
			{td,[],[{input,[{name,"pre_out_notify_cond"},{value,C#vendor_cfg.pre_out_notify_cond}],[
							]}]}
		]}
	]},
	{input,[{type,"submit"},{value,"提交"}],[]}
	]}.
	

	
	

	
ui(basic_info,Vendor_Id) ->
	Vendor = vendor_service:get(list_to_binary(Vendor_Id)),
	io:format("id:~p  vendor:~p~n",[Vendor_Id,Vendor]),
	toForm(Vendor);

ui(cfg_info,Vendor_Id) ->
	toForm(vendor_service:get({cfg,list_to_binary(Vendor_Id)})).